import React, { Component } from 'react'
import { connect } from "react-redux"
import { bindActionCreators } from 'redux'
import * as cartActions from '../store/actions/cart'


class Cart extends Component {
 
  componentDidMount(){
    const {get_product_from_cart } = this.props
    get_product_from_cart()
  }
  handleCount = (productId, ev) => {
    // console.log(99)
    // console.log(ev.target.value)
    // 获取商品的数量
    const count = ev.target.value
    // jie构指令
    const { modify_cart_mount } = this.props
    // 触发指令
    modify_cart_mount({productId, count})
  }
  render() {
    // console.log(this.props)
    const { carts, delete_product_from_cart } = this.props
    return (
      <section className="container content-section">
        {JSON.stringify(carts)}
        <h2 className="section-header">购物车</h2>
        <div className="cart-row">
          <span className="cart-item cart-header cart-column">商品</span>
          <span className="cart-price cart-header cart-column">价格</span>
          <span className="cart-quantity cart-header cart-column">数量</span>
        </div>
        {
          carts.map(product => (
            <div className="cart-items" key={product.id}>
              <div className="cart-row">
                <div className="cart-item cart-column">
                  <img className="cart-item-image" alt='01' src={`http://localhost:3005/${product.thumbnail}`} width="100" height="100" />
                  <span className="cart-item-title">{product.title}</span>
                </div>
                <span className="cart-price cart-column">￥{product.price}</span>
                <div className="cart-quantity cart-column">
                  <input className="cart-quantity-input" type="number" value={product.count} onChange={ev => this.handleCount(product.id,ev)} />
                  <button className="btn btn-danger" type="button" 
                  onClick={() => delete_product_from_cart(product.id)}>删除</button>
                </div>
              </div>
            </div>
          ))
        }
        <div className='cart-total'>
          <strong className='cart-total-title'>总价</strong>
          <span className='cart-total-price'>￥{
            carts.reduce((pre, next) => {
              return pre += next.count * next.price
            }, 0)
          }</span>          
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => ({
  carts: state.carts
}) 
const mapDispatchToProps = dispatch => ({
  ...bindActionCreators(cartActions, dispatch)
})


export default connect(mapStateToProps, mapDispatchToProps)(Cart)